package com.example.demo.juc;

/**
 *
 */
public class Test02 {

    static Object lock = new Object();

    static volatile String name = "A";

    static  class  MyThreadA implements  Runnable{
        @Override
        public void run() {
            for (int i = 0; i <10 ; i++) {
                synchronized (lock){
                    while (!name.equals("A")){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("A");
                    name = "B";
                    lock.notifyAll();
                }
            }
        }
    }


    static  class  MyThreadB implements  Runnable{
        @Override
        public void run() {
            for (int i = 0; i <10 ; i++) {
                synchronized (lock){
                    while (!name.equals("B")){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("B");
                    name = "C";
                    lock.notifyAll();
                }
            }
        }
    }


    static  class  MyThreadC implements  Runnable{

        @Override
        public void run() {
            for (int i = 0; i <10 ; i++) {
                synchronized (lock){
                    while (!name.equals("C")){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    System.out.println("C");
                    name = "A";
                    lock.notifyAll();
                }
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new MyThreadA()).start();
        new Thread(new MyThreadB()).start();
        new Thread(new MyThreadC()).start();

    }

}
